/**
 * Created by jaliu on 2015/2/13.
 */
var userService = require('../../services/backoffice/backOffice-userService');
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var moment = require('moment');
var userInvitation = mongoose.model('user_invitation');

//=================================================== Web后台管理 ============================================


/**
 * 获取全部小区
 */
exports.getAllCommunity = function (req, res) {
    logger.debug('Trying to get the community List ');
    userService.getAllCommunityService(function (err, result) {
        if (err) {
            logger.error("Failed to get the community List by keyword ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by keyword ! " + err.message));
        }
        else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.searchFrontendUser = function (req, res) {
    var startPage = req.params.startPage;
    var pageSize = req.params.pageSize;
    var communityObjId = req.params.communityObjId;
    var nickName = req.params.nickName;
    var mobilePhone = req.params.mobilePhone;
    var isVUser = req.params.isVUser;
    var isTalent = req.params.isTalent;
    var userRole = req.params.userRole;
    var startDate = req.params.startDate;
    var endDate = req.params.endDate;

    if (startPage == null)startPage = 0;
    if (pageSize == null)pageSize = global.listPageSize;
    userService.searchFrontendUserService(communityObjId, mobilePhone, nickName, isVUser, isTalent, userRole, startDate, endDate, startPage, pageSize, function (err, results) {
        if (err) {
            logger.error('Exception happened when searching front end user ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (results == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                var tempResult = {
                    'totalNum': Math.ceil(results[0] / 20),
                    'items': results[1]
                }
                res.json(messageUtil.composeSucceededMessage(req, null, tempResult));
            }
        }
    })
};

exports.putFrontendUserToBlacklist = function (req, res) {
    var userObjId = req.params.userObjId;
    var frozenOrNot = req.body.frozenOrNot;
    var reason = req.body.reason;
    userService.putFrontendUserToBlacklistService(userObjId, frozenOrNot, reason, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to put user to blackList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to put user to blackList...!'));
        } else {
            logger.debug("Successfully to put use into blacklist...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
}

exports.setCancelFrontendUserAsTalent = function (req, res) {
    var userObjId = req.params.userObjId;
    var type = req.params.type;
    var talentDesc = req.params.talentDesc;
    userService.setCancelFrontendUserAsTalentService(userObjId, talentDesc, type, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to set/cancel user as talent...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to set/cancel user as talent...!'));
        } else {

            toolUtil.setUserByToken(userObjId);
            if (type == '1') {
                var arg = {
                    userId: userObjId,
                    userRole: 1,
                    userActionType: 2
                };

                arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

                scoreProxy.invoke('addScore', [arg], function (err, reply) {
                    try {
                        var data = JSON.parse(decodeURIComponent(reply));
                        logger.info(data);
                    } catch (e) {
                        logger.error('hessianInvokeAddScore---' + e);
                        logger.info(reply);
                    }
                });
            }

            logger.debug("Successfully to set/cancel user as talent...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

exports.getUserAuthenticationInfo = function (req, res) {
    var communityObjId = req.params.communityObjId;
    userService.getUserAuthenticationInfoService(communityObjId, function (err, result) {
        if (err) {
            logger.error("Failed to get user authentication info... ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get user authentication info... ! " + err.message));
        }
        else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

exports.setCancelVUser = function (req, res) {
    var communityObjId = req.params.communityObjId;
    var userObjId = req.params.userObjId;
    var input = req.body;
    userService.setCancelVUserService(userObjId, communityObjId, input, function (err, results) {
        if (err) {
            logger.error("Failed to set/cancel User As VUser... ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to set/cancel User As VUser... ! " + err.message));
        } else {
            toolUtil.setUserByToken(userObjId);

            var status = 0;
            if (input.authenticationStatus) {
                status = 1;
            } else {
                status = 0;
            }
            //个推
            var content = {
                f: 3,
                vStatus: status
            };
            var pushData = {
                uList: [userObjId],
                content: content
            };
            toolUtil.putMessageTransmissionPushMQ(pushData);

            if (input.authenticationStatus) {
                var arg = {
                    userId: userObjId,
                    userRole: 1,
                    userActionType: 1
                };

                arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

                scoreProxy.invoke('addScore', [arg], function (err, reply) {
                    try {
                        var data = JSON.parse(decodeURIComponent(reply));
                        logger.info(data);
                    } catch (e) {
                        logger.error('hessianInvokeAddScore---' + e);
                        logger.info(reply);
                    }
                });

                if (results[2] != null) {
                    mysqlUtil.generateUserVoucher(results[2], 2, userObjId, function (err, voucher) {
                        if (err) {
                            logger.error(err.message);
                        } else {
                            userInvitation.update({invitee: userObjId}, {
                                score: voucher.value,
                                dateLastModified: new Date(),
                                type: voucher.type
                            }).exec();

                            //放入周排行榜
                            var key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
                            redisClient.ZINCRBY(key, 1, results[2]);

                            //放入总排行榜
                            var totalKey = 'rank:invitation:total';
                            redisClient.ZINCRBY(totalKey, 1, results[2]);
                        }
                    });

                    //TODO 邀请通知

                    var message = {
                        msgType: 'invite',
                        userId: result[2],
                        inviteUserId: userObjId
                    };
                    toolUtil.putMessageBusinessMQ(message);


                    //建立相互关注
                    userService.eachOtherFollowupService(userObjId + '', results[2] + '');
                }
            }
            logger.debug("Successfully to set/cancel User As VUser... ! ");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}


/**
 * User profile update based on the user's userId
 */
exports.updateUser = function (req, res) {

    var id = req.params.userObjId;
    var input = req.body;

    userService.updateService(id, input, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);

            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the user data...!'));
        } else {
            logger.debug("Update user profile successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));

        }
    })
};


exports.searchMobile = function (req, res) {
    var mobile = req.params.mobile;

    userService.searchMobile(mobile, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);

            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get mobile phone data...!'));
        } else {
            logger.debug("Got mobile phone data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getUserInfoByFilter = function (req, res) {
    var input = req.body;

    userService.getUserInfoByFilterService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to get the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get user data...!'));
        } else {
            logger.debug("Got user data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.addNumberGroup = function (req, res) {
    var input = req.body;
    var groupName = req.params.groupName;
    userService.addNumberGroupService(input, groupName, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to add numberGroup data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to add numberGroup data...!'));
        } else {
            logger.debug("add numberGroup data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


exports.getNumberGroup = function (req, res) {
    var input = req.body;

    userService.getNumberGroupService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to get the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get user data...!'));
        } else {
            logger.debug("Got user data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


exports.updateNumberGroup = function (req, res) {
    var input = req.body;
    var groupId = req.params.groupId;
    var groupName = req.params.groupName;

    userService.updateNumberGroupService(input, groupId, groupName, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update numberGroup data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update numberGroup data...!'));
        } else {
            logger.debug("update numberGroup data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.deleteNumberGroup = function (req, res) {
    var groupId = req.params.groupId;

    userService.deleteNumberGroupService(groupId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update numberGroup data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update numberGroup data...!'));
        } else {
            logger.debug("update numberGroup data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getNumberGroupById = function (req, res) {
    var groupId = req.params.groupId;

    userService.getNumberGroupByIdService(groupId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update numberGroup data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update numberGroup data...!'));
        } else {
            logger.debug("update numberGroup data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getUserByFilter = function (req, res) {
    var input = req.body;

    userService.getUserByFilterService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to get the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get user data...!'));
        } else {
            logger.debug("Got user data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getUserInfoByCommunity = function (req, res) {
    var input = req.body;

    userService.getUserInfoByCommunityService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to get the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get user data...!'));
        } else {
            logger.debug("Got user data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getNumberGroupByFilter = function (req, res) {
    var input = req.body;

    userService.getNumberGroupByFilterService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to get numberGroup data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to get numberGroup data...!'));
        } else {
            logger.debug("get numberGroup data successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};
